package com.homeparking.common.utils;

import java.util.concurrent.TimeUnit;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.homeparking.common.utils.http.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import com.homeparking.common.core.redis.RedisCache;
import org.springframework.stereotype.Component;
// 微信工具类
@Component
public class WeChatUtils {

    @Value("${wechat.appId}")
    private String appId;

    @Value("${wechat.appSecret}")
    private String appSecret;

    @Autowired
    private RedisCache redisCache; // 车位家集成的Redis缓存工具

    /**
     * 获取access_token
     */
    public String getAccessToken() {
        // 从缓存中获取
        String token = redisCache.getCacheObject("wechat_access_token");
        if (StringUtils.isNotEmpty(token)) {
            return token;
        }

        // 请求微信接口
        String url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", appId, appSecret);


        String response = HttpUtils.sendGet(url);


        // 解析响应
        JSONObject json = JSON.parseObject(response);
        if (json != null && json.containsKey("access_token")) {
            token = json.getString("access_token");
            int expiresIn = json.getIntValue("expires_in");//7200
            // 缓存token，提前5分钟过期
            redisCache.setCacheObject("wechat_access_token", token, expiresIn - 500, TimeUnit.SECONDS);
            return token;
        }else{
            return null;
        }
    }

    // 获取手机号
    public String getPhoneNumber(String code) {
        String accessToken = getAccessToken();

        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken;
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("code", code);
        String response = HttpUtils.sendPost(url,jsonParam,"application/json;charset=UTF-8");



        // 解析响应
        JSONObject result = JSON.parseObject(response);
        if (result.getInteger("errcode") == 0) {
            JSONObject phoneInfo = result.getJSONObject("phone_info");
            return phoneInfo.getString("purePhoneNumber"); // 手机号
        } else {
            throw new RuntimeException("获取手机号失败: " + result);
        }
    }
    // 获取openid
    public JSONObject getWxOpenid(String code) {
        // 请求微信接口
        String url = String.format("https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code&appid=%s&secret=%s&js_code=%s", appId, appSecret,code);


        String response = HttpUtils.sendGet(url);


        return JSON.parseObject(response);
    }
}
